package cn.com.thinker.security.sdk.config;

import cn.com.thinker.tools.StringUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by crazyHC on 2017/6/27.
 */
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
public class HttpSessionConfig {


    @Autowired
    private ServerSessionCookie serverSessionCookie;

    /**
     * 请求服务器返回thinker-auth-token值。
     * 浏览器需要自行绑定thinker-auth-token值到header发送到服务器
     * @return
     */
//    @Bean
//    public HttpSessionStrategy httpSessionStrategy() {
//        HeaderHttpSessionStrategy sessionStrategy = new HeaderHttpSessionStrategy();
//        sessionStrategy.setHeaderName("thinker-auth-token");
//        return sessionStrategy;
//    }

    @Bean
    public HttpSessionStrategy httpSessionStrategy() {
        CookieHttpSessionStrategy sessionStrategy = new CookieHttpSessionStrategy();
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        serializer.setCookieName(serverSessionCookie.getName());
        String domain = serverSessionCookie.getDomain();
        if(StringUtils.isNotBlank(domain)) {
            serializer.setDomainName(domain);
        }
        String path = serverSessionCookie.getPath();
        if(StringUtils.isNotBlank(path)){
            serializer.setCookiePath(path);
        }
        // 考虑兼容http情况，设置为false
        // 设置为true时，http请求不会设置cookie。
        serializer.setUseSecureCookie(serverSessionCookie.getSecure());
        Integer maxAge = serverSessionCookie.getMaxAge();
        if(maxAge!=null) serializer.setCookieMaxAge(maxAge);
        sessionStrategy.setCookieSerializer(serializer);
        return sessionStrategy;
    }

    //这里有个小坑，如果服务器用的是云服务器，不加这个会报错
    @Bean
    public static ConfigureRedisAction configureRedisAction() {
        return ConfigureRedisAction.NO_OP;
    }

    @Configuration @Data
    @ConfigurationProperties("server.session.cookie")
    public class ServerSessionCookie{
        private String name="THINSSION";
        private String domain;
        private Integer maxAge=-1;
        private String path;
        private Boolean secure=false;
        private Boolean httpOnly=true;
    }
}
